package com.aoxon.cargo.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.aoxon.cargo.R;
import com.aoxon.cargo.bean.ClothType;
import com.aoxon.cargo.bean.GsonBean;
import com.aoxon.cargo.bean.Type;
import com.aoxon.cargo.loader.FileLoader;
import com.aoxon.cargo.loader.NormalDataLoader;
import com.aoxon.cargo.service.GoodsFilterService;
import com.aoxon.cargo.service.MyServiceFactory;
import com.aoxon.cargo.service.SearchGoodsTipsService;
import com.aoxon.cargo.service.SupGetClassifyListService;
import com.aoxon.cargo.state.MyStateUtil;
import com.aoxon.cargo.util.CheckStateUtil;
import com.aoxon.cargo.util.DataUtil;
import com.aoxon.cargo.util.DisplayUtil;
import com.aoxon.cargo.view.MyGridView;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

/**
 * 采购端搜索页面
 * 
 * @author ZZJ
 * 
 */
public class PurGoodsSearchActivity extends BaseActivity implements
		NormalDataLoader.OnLoadDataListener {

	private ImageView ivReturnButton;
	private TextView tvTitle;
	private List<GridAdapter> adapters = new ArrayList<GridAdapter>();
	private EditText etSearchText;
	private int index;
	private LinearLayout llSearchTipHolder;

	private NormalDataLoader normalDataLoader = new NormalDataLoader(this);

	private FileLoader imageLoader = new FileLoader(100, 100, false);
	private SearchGoodsTipsService searchGoodsTipsService = (SearchGoodsTipsService) MyServiceFactory
			.getInstance(MyServiceFactory.SEARCH_GOODS_TIPS);
	private GoodsFilterService goodsFilterService = (GoodsFilterService) MyServiceFactory
			.getInstance(MyServiceFactory.GOODS_FILTER);
	private SupGetClassifyListService supGetClassifyListService = (SupGetClassifyListService) MyServiceFactory
			.getInstance(MyServiceFactory.SUPGETCLASSIFY);
	private static final int REFLASH_TYPETWO = 1;
	private String strSearchText = new String();
	private List<String> tips = new ArrayList<String>();
	private List<Type> types = new ArrayList<Type>();
	private LayoutInflater inflater;

	private int oneStartIndex = 0;
	private int oneLength = 100;
	private int twoStartIndex = 0;
	private int twoLength = 5;
	private int loadType = 0;

	private int width;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		width = metric.widthPixels; // 屏幕宽度（像素）

		setup();
		loadType = 1;
		normalDataLoader.load();
	}

	private void setup() {
		setContentView(R.layout.pur_search_goods);
		inflater = getLayoutInflater();
		ivReturnButton = (ImageView) findViewById(R.id.ivPublicTitleReturn);
		tvTitle = (TextView) findViewById(R.id.tvPublicTiTle);
		etSearchText = (EditText) findViewById(R.id.etPublicSearchText);

		llSearchTipHolder = (LinearLayout) findViewById(R.id.llPurSearchGoodsTipList);

		tvTitle.setText("找商品");
		etSearchText.setHint("请输入商品名称");

		ivReturnButton.setOnClickListener(myClickListener);
		etSearchText.addTextChangedListener(myTextWatcher);

		normalDataLoader.setOnloadDataListener(this);

		// 设置图片的高度为图片的宽度
		LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) etSearchText
				.getLayoutParams();
		params.width = width - DisplayUtil.dip2px(this, 78);
		etSearchText.setLayoutParams(params);
	}

	/**
	 * 显示搜索提示
	 */
	private void showTip() {
		for (int i = 0; i < tips.size(); i++) {
			final String tip = tips.get(i);
			View tipItem = getLayoutInflater().inflate(
					R.layout.pur_search_tip_text, null);
			TextView textView = (TextView) tipItem
					.findViewById(R.id.tvPurSearchGoodsTip);
			textView.setText(tip);

			tipItem.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(getBaseContext(),
							PurGoodsSearchShowActivity.class);
					intent.putExtra("searchText", tip);
					startActivity(intent);
				}
			});

			llSearchTipHolder.addView(tipItem);

		}
	}

	/**
	 * 显示筛选分类
	 */
	private void showFilterSort() {
		if (types != null) {
			for (int i = 0; i < types.size(); i++) {
				try {
					View typeItem = getLayoutInflater().inflate(
							R.layout.pur_search_goods_item, null);

					ImageView ivPicture = (ImageView) typeItem
							.findViewById(R.id.ivPurSearchGoodsItemPicture);
					TextView tvClassOne = (TextView) typeItem
							.findViewById(R.id.tvPurSearchGoodsItemClassOne);
					TextView tvClasstwo = (TextView) typeItem
							.findViewById(R.id.tvPurSearchGoodsItemClassTwo);
					ProgressBar progressBar = (ProgressBar) typeItem
							.findViewById(R.id.pbPurSearchGoodsItem);
					MyGridView gvClasstwoDetail = (MyGridView) typeItem
							.findViewById(R.id.gvPurSearchGoodsItemTwo);

					String url = types.get(i).getOneType().getPictures().get(0)
							.getPictureUrl()
							+ "s.png";
					final String strClassOne = types.get(i).getOneType()
							.getClothType();
					String strClassTwo = "";

					imageLoader
							.displayImage(url, ivPicture, progressBar, false);
					tvClassOne.setText(strClassOne);

					for (int j = 0; j < types.get(i).getTwoType().size()
							&& j < 5; j++) {

						strClassTwo += types.get(i).getTwoType().get(j)
								.getClothType()
								+ "  ";
					}
					tvClasstwo.setText(strClassTwo);
					GridAdapter adapter = new GridAdapter(types.get(i));
					gvClasstwoDetail.setAdapter(adapter);
					adapters.add(adapter);
					final int index = i;
					typeItem.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View view) {
							// TODO Auto-generated method stub
							for (int i = 0; i < llSearchTipHolder
									.getChildCount(); i++) {
								if (llSearchTipHolder.getChildAt(i)
										.equals(view))
									Log.e("index", String.valueOf(i));
							}
							MyGridView gvClasstwoDetail = (MyGridView) view
									.findViewById(R.id.gvPurSearchGoodsItemTwo);

							TextView tvClasstwo = (TextView) view
									.findViewById(R.id.tvPurSearchGoodsItemClassTwo);
							if (gvClasstwoDetail.getVisibility() == View.GONE) {

								new Thread(new Runnable() {
									public void run() {
										if (adapters.get(index).getCount() <= 5) {
											GsonBean gsonBean = supGetClassifyListService
													.getGoodsClassifyTwo(
															0,
															100,
															types.get(index)
																	.getOneType()
																	.getClothType());

											Log.e("typeTwoById_Gson",
													gsonBean.getStrJson());
											try {
												if (CheckStateUtil
														.check(gsonBean)) {
													String[] strs = DataUtil.gson.fromJson(
															gsonBean.getStrJson(),
															String[].class);
													for (int i = 5; i < strs.length; i++) {
														ClothType type = new ClothType();
														type.setClothType(strs[i]);
														adapters.get(index)
																.appendItem(
																		type);
													}

													Message m = new Message();
													Bundle data = new Bundle();
													data.putInt("index", index);
													m.setData(data);
													m.what = REFLASH_TYPETWO;
													mHandler.sendMessage(m);
												}
											} catch (JsonSyntaxException e) {
												// TODO Auto-generated catch
												// block
												e.printStackTrace();
											} catch (Exception e) {
												// TODO Auto-generated catch
												// block
												e.printStackTrace();
											}
										}
									}
								}).start();

								gvClasstwoDetail.setVisibility(View.VISIBLE);
								tvClasstwo.setVisibility(View.GONE);
							} else {

								gvClasstwoDetail.setVisibility(View.GONE);
								tvClasstwo.setVisibility(View.VISIBLE);
								view.setId(1);
							}
							new Thread(new Runnable() {
								public void run() {

								}
							}).start();
						}
					});

					llSearchTipHolder.addView(typeItem);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 输入框编辑监听
	 */
	TextWatcher myTextWatcher = new TextWatcher() {
		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			// TODO Auto-generated method stub
		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			// TODO Auto-generated method stub
		}

		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			llSearchTipHolder.removeAllViews();
			strSearchText = etSearchText.getText().toString();
			if (strSearchText.equals("")) {
				showFilterSort();
			} else {
				tips.clear();
				tips.add(strSearchText);
				loadType = 2;
				normalDataLoader.load();
			}
		}
	};

	/**
	 * 页面其他按钮的点击监听
	 */
	OnClickListener myClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			Intent intent = null;
			switch (v.getId()) {

			case R.id.ivPublicTitleReturn:
				intent = new Intent(getBaseContext(), CargoActivity.class);
				CargoActivity.OPEN_CHOOSE = MyStateUtil.OPEN_INDEX;
				startActivity(intent);
				PurGoodsSearchActivity.this.finish();
				break;
			default:
				break;
			}

		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			CargoActivity.OPEN_CHOOSE = MyStateUtil.OPEN_INDEX;
			Intent intent = new Intent(getBaseContext(), CargoActivity.class);
			startActivity(intent);
			this.finish();
			return false;
		}
		return false;
	}

	@Override
	public void beforeLoad() {
		// TODO Auto-generated method stub

	}

	@Override
	public void toLoad(Message msg) throws Exception {
		// TODO Auto-generated method stub
		if (1 == loadType) {
			GsonBean gsonBean = goodsFilterService.execute(oneStartIndex,
					oneLength, twoStartIndex, twoLength);
			Log.e("gson", gsonBean.getStrJson());
			if (CheckStateUtil.check(gsonBean)) {
				List<Type> typeList = DataUtil.gson.fromJson(
						gsonBean.getStrJson(), new TypeToken<List<Type>>() {
						}.getType());
				types.addAll(typeList);
			}
			msg.what = MyStateUtil.SEARCH__FILTERSORT_SHOW;

		} else {
			GsonBean gsonBean = searchGoodsTipsService.execute(0, 10,
					strSearchText);
			if (CheckStateUtil.check(gsonBean)) {
				List<String> tipList = DataUtil.gson.fromJson(
						gsonBean.getStrJson(), new TypeToken<List<String>>() {
						}.getType());
				tips.addAll(tipList);
			}
			msg.what = MyStateUtil.SEARCH_TIP_SHOW;
		}
	}

	@Override
	public void afterLoad(int state) {
		// TODO Auto-generated method stub
		llSearchTipHolder.removeAllViews();
		switch (state) {
		case MyStateUtil.SEARCH__FILTERSORT_SHOW:
			showFilterSort();
			break;
		case MyStateUtil.SEARCH_TIP_SHOW:
			showTip();
			break;
		default:
			break;
		}
	}

	class GridAdapter extends BaseAdapter {
		Type mType;

		public GridAdapter(Type mType) {
			this.mType = mType;
		}

		public void appendItem(ClothType twoType) {
			mType.getTwoType().add(twoType);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mType.getTwoType().size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int pisition, View view, ViewGroup arg2) {
			// TODO Auto-generated method stub
			if (view == null) {
				view = getLayoutInflater().inflate(
						R.layout.pur_search_goods_item_second, null);
			}
			((TextView) view).setText(mType.getTwoType().get(pisition)
					.getClothType());
			view.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View tv) {
					// TODO Auto-generated method stub

					Intent intent = new Intent(getBaseContext(),
							PurGoodsSearchShowActivity.class);
					intent.putExtra("searchText", ((TextView) tv).getText());
					startActivity(intent);
				}

			});

			return view;
		}

	}

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			if (msg.what == REFLASH_TYPETWO) {
				int i = msg.getData().getInt("index", -1);
				if (i != -1) {
					adapters.get(i).notifyDataSetChanged();
				}
			}
			super.handleMessage(msg);
		}

	};
}